import {getVKey, getLyric} from 'api/song'
import {ERR_OK} from 'api/config'
import {Base64} from 'js-base64'

export default class Song {
  constructor({id, mid, singer, name, album, duration, filename, image, url, vip}) {
    if (vip) {
      name = name + ' · vip'
    }
    this.id = id
    this.mid = mid
    this.singer = singer
    this.name = name
    this.album = album
    this.duration = duration
    this.filename = filename
    this.image = image
    this.vip = vip
    // 歌曲URL
    this.url = url
    // 歌曲URL携带的vkey有效期
    this.keyExpires = false
    // 歌词
    this.lyric = false
  }
  // 获取vkey
  getVKey () {
    let timestamp = new Date().getTime() / 1000 | 0
    if (this.keyExpires && this.keyExpires > timestamp) {
      return Promise.resolve(this.url)
    }
    let url = this.url
    url = url.substring(0, url.lastIndexOf('=') + 1)
    return new Promise((resolve, reject) => {
      // 获取vkey,并设置歌曲url及expires
      getVKey(this.mid, this.filename).then((res) => {
        if (res.code === ERR_OK) {
          this.keyExpires = timestamp + res.data.expiration
          this.url = url + res.data.items[0].vkey
          resolve(this.url)
        } else {
          reject(new Error('no vkey'))
        }
      })
    })
  }
  // 获取歌词
  getLyric () {
    if (this.lyric) {
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getLyric(this.mid).then((res) => {
        if (res.retcode === ERR_OK) {
          this.lyric = Base64.decode(res.lyric)
          resolve(this.lyric)
        } else {
          reject(new Error('no lyric'))
        }
      })
    })
  }
}

export function createSong(musicData) {
  return new Song({
    id: musicData.songid,
    mid: musicData.songmid,
    singer: filterSinger(musicData.singer),
    name: musicData.songname,
    album: musicData.albumname,
    duration: musicData.interval,
    filename: `C400${musicData.songmid}.m4a`,
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
    url: `http://dl.stream.qqmusic.qq.com/C400${musicData.songmid}.m4a?uin=0&romtag=66&guid=8773688539&vkey=`,
    vip: musicData.pay.payplay
  })
}

function filterSinger(singer) {
  let ret = []
  if (!singer) {
    return ''
  }
  singer.forEach((s) => {
    ret.push(s.name)
  })
  return ret.join('/')
}
